// 1.--------组件重新加载 reload
// -----2获取组件数据-------------getData---------------
// 3-------------------- 设置组件值 setData--------------------
// 4.----------添加查询条件 addSearchData-------

import * as Blockly from 'blockly/core'
import { getAllAddSearchDataComponent, getAllReloadComponent, getAllGetDataComponent } from '../utils/component'
import { getContextText } from '../utils/block'

Blockly.Extensions.register('dynamic_common_component_extension',
  function () {
    var that = this
    let comList = []
    if (this.type === 'component_reload') {
      comList = getAllReloadComponent()
    } else if (this.type === 'component_assign_query') {
      comList = getAllAddSearchDataComponent()
    }
    const dropdown = new Blockly.FieldDropdown(
      function () {
        var options = []
        if (!comList.length) {
          options = [['没有数据', 'noData']]
          return options
        }
        for (var i = 0; i < comList.length; i++) {
          const com = comList[i]
          const label = (com?.modelName) ? (com?.__config?.label) : ''
          var dateString = com.name + label + '（' + com.key + '）'
          options.push([dateString, com.key])
        }
        return options
      })
    this.getInput('COMPONENT_INPUT').appendField(dropdown, 'Component')
  })

// 1.--------组件重新加载 reload------------
const componentReloadJson = {
  type: 'component_reload',
  message0: '重新加载 %1',
  args0: [
    // 动态生成选项
    {
      'type': 'input_dummy',
      'name': 'COMPONENT_INPUT'
    }
  ],
  extensions: ['dynamic_common_component_extension'],
  previousStatement: null,
  nextStatement: null,
  style: 'action_blocks',
  inputsInline: true,
  mutator: 'reload_mutator',
  tooltip: '',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['component_reload'] = {
  init: function () {
    this.jsonInit(componentReloadJson)
  }
}

Blockly.JavaScript['component_reload'] = function (block) {
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  const options = Blockly.JavaScript.valueToCode(block, 'PARAM_OPTIONS',
    Blockly.JavaScript.ORDER_COMMA) || '{}'

  let code = `${context}.getComponent('${compVar}').dispatch('reload')`
  if (block.paramCount_) {
    code = `${context}.getComponent('${compVar}').dispatch('reload', ${options})`
  }
  return code + '\n'
}

// -----2获取组件数据-------------getData---------------

Blockly.Extensions.register('dynamic_get_data_component_extension',
  function () {
    var that = this
    const jsonType = ['hlProcess']
    const comList = getAllGetDataComponent()
    const validator = function (newValue) {
      const compVar = that.getFieldValue('Component') // 组件的key
      const com = comList.find(item => item.key === compVar)
      if (!com) return
      const comType = com.tagName
      if (that.type === 'component_get_data') {
        if (jsonType.includes(comType)) {
          that.setOutput(true, 'Object')
        } else {
          that.setOutput(true, 'Array')
        }
      } else if (that.type === 'component_set_data') {
        if (jsonType.includes(comType)) {
          that.getInput('DATA').setCheck('Object')
        } else {
          that.getInput('DATA').setCheck('Array')
        }
      }
    }
    const dropdown = new Blockly.FieldDropdown(
      function () {
        var options = []
        if (!comList.length) {
          options = [['没有数据', 'noData']]
          return options
        }
        for (var i = 0; i < comList.length; i++) {
          const com = comList[i]
          const label = (com?.modelName) ? (com?.__config?.label) : ''
          var dateString = com.name + label + '（' + com.key + '）'
          options.push([dateString, com.key])
        }
        return options
      })
    dropdown.setValidator(validator)
    this.getInput('COMPONENT_INPUT').appendField(dropdown, 'Component')
  })

const componentGetDataJson = {
  type: 'component_get_data',
  message0: '获取组件 %1 数据 ',
  args0: [
    {
      'type': 'input_dummy',
      'name': 'COMPONENT_INPUT'
    }
  ],
  extensions: ['dynamic_get_data_component_extension'],
  output: null,
  inputsInline: true,
  style: 'action_blocks',
  tooltip: '',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['component_get_data'] = {
  init: function () {
    this.jsonInit(componentGetDataJson)
  }
}

Blockly.JavaScript['component_get_data'] = function (block) {
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  const code = `${context}.getComponent('${compVar}').dispatch('getData')`
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]
}

// -3-------------------- 设置组件值 setData--------------------
const componentSetDataJson = {
  type: 'component_set_data',
  message0: '设置组件 %1 数据 为 %2',
  args0: [
    {
      'type': 'input_dummy',
      'name': 'COMPONENT_INPUT'
    },
    {
      'type': 'input_value',
      'name': 'DATA'
    }
  ],
  extensions: ['dynamic_get_data_component_extension'],
  // output: null,
  inputsInline: true,
  previousStatement: null,
  nextStatement: null,
  style: 'action_blocks',
  tooltip: '',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['component_set_data'] = {
  init: function () {
    this.jsonInit(componentSetDataJson)
  }
}

Blockly.JavaScript['component_set_data'] = function (block) {
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  const data = Blockly.JavaScript.valueToCode(block, 'DATA',
    Blockly.JavaScript.ORDER_COMMA) || 'null'
  const code = `${context}.getComponent('${compVar}').dispatch('setData', ${data})`
  return code + '\n'
}

// 4.----------添加查询条件 addSearchData-------------------------------------------
const queryJson = {
  type: 'component_assign_query',
  message0: '组件%1添加查询条件%2',
  args0: [
    // 动态生成选项
    {
      'type': 'input_dummy',
      'name': 'COMPONENT_INPUT'
    },
    {
      type: 'input_value',
      name: 'QUERY_DATA'
    }
  ],
  extensions: ['dynamic_common_component_extension'],
  previousStatement: true,
  nextStatement: true,
  inputsInline: true,
  style: 'action_blocks',
  tooltip: '表格添加表格的查询条件',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['component_assign_query'] = {
  init: function () {
    this.jsonInit(queryJson)
  }
}

Blockly.JavaScript['component_assign_query'] = function (block) {
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  const queryObj = Blockly.JavaScript.valueToCode(block, 'QUERY_DATA',
    Blockly.JavaScript.ORDER_COMMA) || `{}`
  const code = `${context}.getComponent('${compVar}').dispatch('addSearchData',${queryObj})`
  return code + '\n'
}

// reload的mutator

const mixinObj = {
  mutationToDom: function () {
    var container = Blockly.utils.xml.createElement('mutation')
    container.setAttribute('param', this.paramCount_)
    return container
  },
  domToMutation: function (xmlElement) {
    this.paramCount_ = parseInt(xmlElement.getAttribute('param'), 10) || 0
    this.updateShape_()
  },
  updateShape_: function () {
    if (this.paramCount_) {
      const connection = this.getInput('PARAM_OPTIONS')?.connection?.targetConnection
      if (this.getInput('PARAM_OPTIONS')) {
        this.removeInput('PARAM_OPTIONS')
      }
      const input = this.appendValueInput('PARAM_OPTIONS').setCheck('Object')
      input.appendField('查询条件')
      Blockly.Mutator.reconnect(connection, this, 'PARAM_OPTIONS')
    } else {
      if (this.getInput('PARAM_OPTIONS')) {
        this.removeInput('PARAM_OPTIONS')
      }
    }
  }
}

const helpFun = function () {
  this.paramCount_ = 0
  this.updateShape_()
}

Blockly.Extensions.registerMutator('reload_mutator',
  mixinObj, helpFun)
